const app = getApp();
Page({
  data: {
    user: null,
    lover: null,
    islogin: false,
    code: '',
    showbind: false,
  },
  onLoad() {
    let user = wx.getStorageSync('user')
    let lover = wx.getStorageSync('lover')
    if (user && lover) {
      app.globalData.islogin = true //全局是否登陆信息
      this.setData({
        user: user,
        lover: lover,
        islogin: true,
      })
    }
  },
  login() {
    let openid
    wx.cloud.callFunction({ // 获取openid
      name: "getOpenid"
    }).then(res => {
      openid = res.result.openid
    })
    wx.getUserProfile({ // 授权登陆
      desc: '必须授权',
    }).then(res => {
      app.globalData.islogin = true
      this.data.user = res.userInfo
      this.data.user.lover = ""
      this.data.user._openid = openid
      this.getByOpenid(this.data.user._openid).then(res => {
        if (res.data.length <= 0) {  // 新用户绑定对象和注册入数据库
          this.setData({
            islogin: true,
            showbind: true,
            user: this.data.user
          })
          wx.cloud.database().collection('users').add({
            data: {
              avatarurl: this.data.user.avatarUrl,
              nickname: this.data.user.nickName,
              lover: this.data.user.lover
            }
          })
        }
        else if (res.data.length > 0 && res.data[0].lover == "") { // 旧用户且无对象
          this.setData({
            islogin: true,
            showbind: true,
            user: this.data.user
          })
        } else {   // 旧用户有对象直接登陆 然后更新最新数据到数据库
          var user = res.data[0]
          this.getByOpenid(user.lover).then(res => {
            this.setData({
              islogin: true,
              user: user,
              lover: res.data[0]
            })
            wx.setStorageSync('user', this.data.user) // 缓存用户和对象
            wx.setStorageSync('lover', this.data.lover)
            wx.cloud.database().collection('users').doc(this.data.user._id).update({ // 更新最新的用户信息
              data: {
                avatarurl: this.data.user.avatarurl,
                nickname: this.data.user.nickname,
              }
            })
          })
        }
      })
    })
  },
  bindlovers() {
    if (this.data.code == '') {
      wx.showToast({
        icon: "none",
        title: '生成码不能为空',
      })
      return
    }else if(this.data.code == this.data.user._openid){
      wx.showToast({
        icon: "none",
        title: '不能与自己绑定哦',
      })
      return
    }
    // 对两个用户的情侣关系进行更新
    wx.showLoading({
      title: '绑定中',
    })
    this.getByOpenid(this.data.user._openid).then(res => {
      this.data.user = res.data[0]
      this.getByOpenid(this.data.code).then(res => {
        this.data.lover = res.data[0]
        this.data.lover.lover = this.data.user._openid
        this.data.user.lover = this.data.lover._openid
        wx.cloud.callFunction({
          name: 'updateUser',
          data: {
            user: this.data.user
          }
        }).then(res => {
          wx.cloud.callFunction({
            name: "updateUser",
            data: {
              user: this.data.lover
            }
          }).then(res => {
            this.setData({
              showbind: false,
              user: this.data.user,
              lover: this.data.lover
            })
            wx.setStorageSync('user', this.data.user)
            wx.setStorageSync('lover', this.data.lover)
            wx.hideLoading()
            wx.showToast({
              title: '绑定成功',
            })
          })
        })
      })
    })

  },
  onReady() {
    wx.cloud.database().collection('users').watch({ // 监听是否对方是否绑定
      onChange: this.refresh.bind(this),
      onError(err) {
        console.error(err)
      }
    })
  },
  refresh(snapshot) {
    if (snapshot.docChanges[0].dataType == "update" && snapshot.docChanges[0].doc._openid == this.data.user._openid && snapshot.docChanges[0].doc.lover != "") {
      this.getByOpenid(this.data.user._openid).then(res => {
        var user = res.data[0]
        this.getByOpenid(user.lover).then(res => {
          this.setData({
            user: user,
            lover: res.data[0],
            showbind: false
          })
          wx.setStorageSync('user', this.data.user)
          wx.setStorageSync('lover', this.data.lover)
        })
      })
    }
  },
  logout() {
    app.globalData.islogin = false
    this.setData({
      user: null,
      islogin: false
    })
    wx.setStorageSync('user', null)
    wx.setStorageSync('lover', null)
  },
  copyText() {
    wx.setClipboardData({
      data: this.data.user._openid,
    }).then(res => {
      wx.showToast({
        title: '复制成功',
      })
    })
  },
  getInput(e) {
    this.setData({
      code: e.detail.value
    })
  },
  getByOpenid(openid) {
    return wx.cloud.database().collection('users').where({ //如果是第一次登陆则添加入数据库
      _openid: openid
    }).get()
  },
})